// client.go
package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"os"
	"time"
)

func main() {
	conn, err := net.DialTimeout("tcp", "127.0.0.1:9000", 5*time.Second)
	if err != nil {
		log.Fatalf("dial error: %v", err)
	}
	defer conn.Close()

	log.Printf("已连接服务器：remote=%s local=%s", conn.RemoteAddr(), conn.LocalAddr())

	// 向服务器发送多条消息
	msgs := []string{"你好，TCP", "Hello, Go", "quit"}
	for _, msg := range msgs {
		if _, err := fmt.Fprintf(conn, "%s\n", msg); err != nil {
			log.Fatalf("write error: %v", err)
		}
	}

	// 读取服务器回显
	reader := bufio.NewReader(conn)
	for range msgs {
		reply, err := reader.ReadString('\n')
		if err != nil {
			log.Fatalf("read error: %v", err)
		}
		fmt.Printf("收到响应: %s", reply)
	}

	log.Println("客户端执行完毕，准备退出")
	// defer 的 Close 会触发正常的四次挥手
	os.Exit(0)
}
